package com.zzedu.framework.aspectj;

import com.zzedu.common.utils.IpUtils;
import com.zzedu.common.utils.uuid.IdUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Order(1000)
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)||@annotation(org.springframework.web.bind.annotation.RequestMapping)||@annotation(org.springframework.web.bind.annotation.PostMapping)||@annotation(org.springframework.web.bind.annotation.DeleteMapping)||@annotation(org.springframework.web.bind.annotation.PutMapping)")
    public void logPointCut() {
    }


    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        try {
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            MDC.put("traceId", IdUtils.fastSimpleUUID());
            MDC.put("ip", IpUtils.getIpAddr(request));
            // 记录下请求内容
            logger.info("请求IP : " + IpUtils.getIpAddr(request));
            logger.info("请求地址 : " + request.getRequestURL().toString());
            logger.info("HTTP METHOD : " + request.getMethod());
            // 获取真实的ip地址
            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                    + joinPoint.getSignature().getName());
            logger.info("参数 : " + JSON.toJSONString(joinPoint.getArgs()));
        } catch (Exception e) {

        }
    }


    @AfterReturning(returning = "ret", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
    public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
        // 处理完请求，返回内容(返回值太复杂时，打印的是物理存储空间的地址)
        logger.info("返回值 : " + JSON.toJSONString(ret, SerializerFeature.DisableCircularReferenceDetect));
        MDC.clear();
    }


    @AfterThrowing(throwing = "ex", pointcut = "logPointCut()")// returning的值和doAfterReturning的参数名一致
    public void doAfterReturning(Throwable ex) throws Throwable {
        // 处理完请求，返回内容(返回值太复杂时，打印的是物理存储空间的地址)
        logger.error("执行错误,详细:{}",ex.getMessage());
        MDC.clear();
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        MDC.put("traceId", IdUtils.fastSimpleUUID());
        MDC.put("ip", IpUtils.getIpAddr(request));
        // ob 为方法的返回值
        Object ob = pjp.proceed();
        logger.info("耗时 : " + (System.currentTimeMillis() - startTime));
        return ob;
    }
}
